/*
 * Copyright 2014 JooKar (info@jookar.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.jookar.privatechat.model;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import nl.jookar.privatechat.bussiness.InvalidAddressException;

/**
 * Represents an Email Address from a User.
 * Is used as id for the {@link User} class.
 * 
 * @author Joost A. Bloemsma
 */
public class EmailAddress {
    private String address;

    /**
     * Constructs a new EmailAddress instance
     * @param address
     * @throws InvalidAddressException
     */
    public EmailAddress(String address) throws InvalidAddressException {
        super();
        this.setAddress(address);
    }
    
    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     * @throws InvalidAddressException 
     */
    public void setAddress(String address) throws InvalidAddressException {
        if (!EmailAddress.isValidAddress(address)) throw new InvalidAddressException();
        this.address = address;
    }
    
    /**
     * Check is the passed string <b>could</b> be a valid email address.
     * Test is done by using {@link InternetAddress#validate()}.
     * @param address
     * @return true if the address <b>could</b> be valid
     */
    public static boolean isValidAddress(String address) {
        try {
            new InternetAddress(address).validate();
        } catch (AddressException e) {
            return false;
        }
        
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return (this.getAddress() == null)?"NULL":this.getAddress();
    }
    
    
    
}

